package com.wanghaibo.vgashow.climatecontrol;

import android.graphics.RectF;

import java.util.Random;

public class AnimParticle implements Cloneable {
    /**
     * 粒子原点x坐标
     */
    private float mX;
    /**
     * 粒子原点y坐标
     */
    private float mY;
    /**
     * 粒子半径
     */
    private float radius;
    /**
     * 粒子初始位置的角度
     */
    private double angle;
    /**
     * 一帧移动的速度
     */
    private float velocity;
    /**
     * 总共移动的帧数
     */
    private int num = 0;

    /**
     * 透明度 0~255
     */
    private int alpha = 153;

    /**
     * 随机偏移角度
     */
    private double randomAngle = 0;

    public void init(Random random, RectF emitterRectF) {
        velocity = random.nextFloat() * 2 + 2;
        radius = random.nextFloat() * 4 + 2;
        mX = random.nextFloat() * emitterRectF.width() + emitterRectF.left;
        mY = random.nextFloat() * emitterRectF.height() + emitterRectF.top;
        //随机偏移角度-30°~30°
        randomAngle = Math.toRadians(30 - random.nextInt(60));
        alpha = 200 + random.nextInt(55);
    }

    /**
     * 想让粒子运动起来，使用update更新粒子的这些坐标属性就能实现，
     * 比如粒子现在坐标在(5,5)，通过update()改变粒子的坐标到(6,6),
     * 结合属性动画不停地调用update()则就能不停的改变x,y的坐标，实现粒子运动，
     * 然后当粒子移动超过一定距离，或者调用update超过一定次数，再重新调用init()让粒子重新从圆周上开始下一个生命周期运动
     * @param random
     * @param emitterRectF
     * @param direction
     */
    public void updateParticle(Random random, RectF emitterRectF, double direction) {
        //每一帧偏移的像素大小
        float distance = 1F;
        double moveAngle = direction + randomAngle;
        mX = (float) (mX - distance * Math.cos(moveAngle) * velocity);
        mY = (float) (mY - distance * Math.sin(moveAngle) * velocity);
        //模拟半径逐渐变小
        radius = radius - 0.05F * velocity;
        num++;
        //如果到了最大值 则重新给运动粒子一个轨迹属性
        int maxDistance = 180;
        int maxNum = 400;
        if (velocity * num > maxDistance || num > maxNum) {
            num = 0;
            init(random, emitterRectF);
        }
    }

    /**
     * 避免重复申请内存，从现有对象clone获得新对象
     *
     * @return
     */
    @Override
    protected AnimParticle clone() {
        AnimParticle animParticle = null;
        try {
            animParticle = (AnimParticle) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return animParticle;
    }

    public float getRadius() {
        return radius;
    }

    public void setRadius(float radius) {
        this.radius = radius;
    }

    public float getmX() {
        return mX;
    }

    public void setmX(float mX) {
        this.mX = mX;
    }

    public float getmY() {
        return mY;
    }

    public void setmY(float mY) {
        this.mY = mY;
    }

    public int getAlpha() {
        return alpha;
    }

    public void setAlpha(int alpha) {
        this.alpha = alpha;
    }
}